//axios请求前后置拦截处理

import axios from "axios";
import router from "./router/router";
import Element from "element-ui"

axios.defaults.baseURL = process.env.BASE_URL
// axios.defaults.baseURL = "http://localhost:8888"


const request = axios.create({
  timeout: 50000,
  // baseURL: "http://43.142.150.186:8888",
  headers: {
    'Content-Type': "application/json; charset=utf-8"
  }
})


//reuqest拦截器
request.interceptors.request.use(
  config => {
    if ((config.url).substring(0, 11) !== "/loginAdmin") {
      config.headers['token'] = localStorage.getItem("token")
    }
    // if (config.method == 'post') {
    //   config.params = config.data;
    // }
    return config
  })


//response拦截器
request.interceptors.response.use(
  response => {
    // console.log("response ->" + response)
    // 二进制数据则直接返回
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
      return response
    }
    let res = response.data
    //拦截是否等于200
    if (res.code === 200) {
      //等于200继续往下面走response
      // console.log(res.data)
      if (res.msg) {
        Element.Message.success(res.msg)
      }
      return response
    } else {
      //弹出异常
      Element.Message.error(!res.msg ? '系统异常' : res.msg)
      return Promise.reject(response.data.msg)
    }
  },
  error => {


    console.log(error)

    //中间业务异常：出现断言、权限异常
    if (error.response.data) {
      error.massage = error.response.data.msg
    }

    //401无权限
    if (error.response.status === 401) {
      router.push("/login")
    }

    //判断error.massage = error.response.data.msg，如果无则返回error.massage
    Element.Message.error(error.massage, { duration: 3000 })
    return Promise.reject(error)
  }
)

//暴露出去
export default request
